package com.fileupload.fileupload.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.errors.*;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucketName;
    private String tempBucket;

    @Bean
    public MinioClient getMinioClient() {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
            // 创建存储桶 , 如果不存在则创建
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
            // 创建临时文件存储桶 , 如果不存在则创建
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(tempBucket).build())) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(tempBucket).build());
            }
            return minioClient;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
